/* Copyright (c) 2021 Xie Meiyi(xiemeiyi@hust.edu.cn) and OceanBase and/or its affiliates. All rights reserved.
miniob is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
         http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details. */

//
// Created by Wangyunlai on 2021/5/12.
//

#include "session/session.h"
#include "storage/trx/trx.h"
#include "storage/common/db.h"
#include "storage/default/default_handler.h"

// 创建一个session对象，并且获取这个session对象
Session &Session::default_session()
{
  static Session session;
  return session;
}
// 构造函数
Session::Session(const Session &other) : db_(other.db_)
{}

// 析构函数
Session::~Session()
{
  delete trx_;
  trx_ = nullptr;
}

// 获取当前数据库的名称
const char *Session::get_current_db_name() const
{
  if (db_ != nullptr)
    return db_->name();
  else
    return "";
}

// 获取当前数据库
// db_是一个DB类
Db *Session::get_current_db() const
{
  return db_;
}

// 重新设置此时的db
// db_是当前的数据库，在这个函数中，把通过db_name找到的db传递给db_
void Session::set_current_db(const std::string &dbname)
{
  DefaultHandler &handler = DefaultHandler::get_default();
  Db *db = handler.find_db(dbname.c_str());
  if (db == nullptr) {
    LOG_WARN("no such database: %s", dbname.c_str());
    return;
  }

  LOG_TRACE("change db to %s", dbname.c_str());
  db_ = db;
}

// 设置当前的事务模式为多语句模式
void Session::set_trx_multi_operation_mode(bool multi_operation_mode)
{
  trx_multi_operation_mode_ = multi_operation_mode;
}

// 判断当前事务模式是否为多事务模式
bool Session::is_trx_multi_operation_mode() const
{
  return trx_multi_operation_mode_;
}

Trx *Session::current_trx()
{
  if (trx_ == nullptr) {
    trx_ = new Trx;
  }
  return trx_;
}
